import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/checkin/checkinmodel.dart';
import 'package:opene/ui/returns/returnsmodel.dart';
import 'package:opene/ui/returns/returnsmodel.dart';
import 'package:opene/utils/ImageUtils.dart';
import 'package:toast/toast.dart';

class FinalProcessSubmitScreen extends StatelessWidget {
  FinalProcessQr finalProcessQr;

  FinalProcessSubmitScreen({this.finalProcessQr});

  @override
  Widget build(BuildContext context) {
    return FinalProcessSubmitPage(finalProcessQr: finalProcessQr);
  }
}

class FinalProcessSubmitPage extends StatefulWidget {
  FinalProcessQr finalProcessQr;

  FinalProcessSubmitPage({this.finalProcessQr});

  @override
  _FinalProcessSubmitPageState createState() => _FinalProcessSubmitPageState(finalProcessQr: finalProcessQr);
}

class _FinalProcessSubmitPageState extends BaseState<FinalProcessSubmitScreen> {
  FinalProcessQr finalProcessQr;

  _FinalProcessSubmitPageState({this.finalProcessQr});

  final controller = ScrollController();

  PhotoBean bolPhoto;

  int index = 0, position;

  final TextEditingController skuEditingController = TextEditingController();

  FocusNode textFiledNode = FocusNode();
  FocusNode skuFocusNode = FocusNode();
  FocusNode qtyFocusNode = FocusNode();

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Returns: Shipment";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setState(() {
      next = "Submit";
      bolPhoto = new PhotoBean();
    });
  }

  @override
  void dispose() {
    textFiledNode.dispose(); // 不要忘记销毁FocusNode
    skuFocusNode.dispose(); // 不要忘记销毁FocusNode
    qtyFocusNode.dispose(); // 不要忘记销毁FocusNode
    super.dispose();
  }

  Future pickImages(context) async {
    File image = await ImageUtils.chosePhotoOnAlbumOrCamera(context: context);
    print(image.path);
    String name = "";
    setState(() {
      bolPhoto.image = image;
      name = "retape";
      fileUpload(finalProcessQr.trackingCode, "finalprocessrp", image, name, index, position, false, false);
      print("index:${index},position:${position}");
      print(image.path);
    });
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Text(
                    "BatchNo: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                  Text(
                    "Original LPN: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                  Text(
                    "TRK#: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                  Visibility(
                      visible: finalProcessQr == null
                          ? false
                          : Utils.isEmpty(finalProcessQr.sku)
                              ? false
                              : true,
                      child: Text(
                        "SKU: ",
                        style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                      )),
                  Text(
                    "QTY: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                  Visibility(
                    visible: finalProcessQr == null
                        ? false
                        : finalProcessQr.accountId == null
                            ? false
                            : true,
                    child: Text(
                      "customer id: ",
                      style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                    ),
                  ),
                ],
              ),
              Expanded(
                child: Column(
                  children: [
                    Text(
                      finalProcessQr == null ? "" : Utils.getStringisEmpty(finalProcessQr.trackingCode),
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    ),
                    Text(
                      finalProcessQr == null ? "" : Utils.getStringisEmpty(finalProcessQr.trackingCode),
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    ),
                    Text(
                      finalProcessQr == null ? "" : Utils.getStringisEmpty(finalProcessQr.trackingCode),
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    ),
                    Visibility(
                      visible: finalProcessQr == null
                          ? false
                          : Utils.isEmpty(finalProcessQr.sku)
                              ? false
                              : true,
                      child: Text(
                        finalProcessQr == null ? "" : Utils.getStringisEmpty(finalProcessQr.sku),
                        style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                      ),
                    ),
                    Text(
                      finalProcessQr == null ? "" : Utils.getStringisEmpty(finalProcessQr.trackingCode),
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    ),
                    Visibility(
                      visible: finalProcessQr == null
                          ? false
                          : finalProcessQr.accountId == null
                              ? false
                              : true,
                      child: Text(
                        finalProcessQr == null ? "" : "${finalProcessQr.accountId}",
                        style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          SizedBox(
            height: 5,
          ),
          Row(
            children: [
              Expanded(
                flex: 1,
                child: ConstrainedBox(
                  constraints: BoxConstraints(maxHeight: 35),
                  child: TextField(
                    focusNode: textFiledNode,
                    controller: textEditingController,
                    textInputAction: TextInputAction.search,
                    onSubmitted: (String text) {
                      print('Searching for $text');
                      if (Utils.isEmpty(text)) {
                        return;
                      }
                    },
                    // autofocus: true,
                    decoration: InputDecoration(
                      suffixIcon: IconButton(
                        padding: EdgeInsets.all(2.0),
                        icon: Icon(
                          Icons.qr_code_scanner,
                          size: 28,
                          color: MyAppTheme.nearlyBlue,
                        ),
                        onPressed: () {
                          // requestPermissions();
                          // Utils.scanBarcode(context);
                          Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                            return ScanCode();
                          })).then((text) {
                            if (text == null) {
                              return;
                            }
                            setState(() {
                              textEditingController.text = text;
                            });
                            print(text); //拿到扫描结果
                          });
                        },
                      ),
                      border: OutlineInputBorder(
                        borderSide: BorderSide(
                          color: MyAppTheme.nearlyBlue,
                        ),
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                        // 设置焦点之外的边框颜色
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                        // 设置焦点时的边框颜色
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      hintText: "scan new inbound lpn",
                      filled: true,
                      fillColor: MyAppTheme.white,
                      //隐藏下划线
                      //border: InputBorder.none,
                      hintStyle: TextStyle(color: Colors.grey),
                      contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                    ),
                    onChanged: (text) {
                      code = text;
                    },
                  ),
                ),
              ),
            ],
          ),
          Visibility(
              visible: finalProcessQr == null
                  ? false
                  : finalProcessQr.type == null
                      ? false
                      : (finalProcessQr.type == "D" || finalProcessQr.type == "D2" || finalProcessQr.type == "P")
                          ? true
                          : false,
              child: Row(
                children: [
                  Text(
                    "*",
                    style: TextStyle(color: MyAppTheme.red, fontSize: 14.0),
                  ),
                  Text(
                    "product label should be replaced to: ",
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                  ),
                ],
              )),
          Visibility(
              visible: finalProcessQr == null
                  ? false
                  : finalProcessQr.type == null
                      ? false
                      : (finalProcessQr.type == "D" || finalProcessQr.type == "D2" || finalProcessQr.type == "P")
                          ? true
                          : false,
              child: Row(
                children: [
                  Expanded(
                      child: Text(
                    finalProcessQr == null
                        ? ""
                        : finalProcessQr.type == null
                            ? ""
                            : (finalProcessQr.type == "D" || finalProcessQr.type == "D2")
                                ? Utils.getStringisEmpty(finalProcessQr.openLassSku)
                                : finalProcessQr.type == "P"
                                    ? Utils.getStringisEmpty(finalProcessQr.newSku)
                                    : "",
                    style: TextStyle(color: MyAppTheme.red, fontSize: 14.0),
                  )),
                  GestureDetector(
                    child: SizedBox(
                      height: 35, // 高度
                      child: ElevatedButton(
                        child: Text(
                          "Print",
                          style: TextStyle(color: MyAppTheme.white, fontSize: 14.0),
                        ),
                        style: ButtonStyle(
                          backgroundColor: MaterialStateProperty.all<Color>(MyAppTheme.nearlyBlue),
                          shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                            RoundedRectangleBorder(
                              borderRadius: const BorderRadius.all(Radius.circular(8.0)),
                            ),
                          ),
                        ),
                        onPressed: () {},
                      ),
                    ),
                  )
                ],
              )),
          Visibility(
            visible: finalProcessQr.type == null
                ? false
                : (finalProcessQr.type == "D" || finalProcessQr.type == "D2" || finalProcessQr.type == "P")
                    ? true
                    : false,
            child: Row(
              children: [
                Expanded(
                  flex: 1,
                  child: ConstrainedBox(
                    constraints: BoxConstraints(maxHeight: 35),
                    child: TextField(
                      focusNode: skuFocusNode,
                      controller: skuEditingController,
                      textInputAction: TextInputAction.search,
                      onSubmitted: (String text) {
                        print('Searching for $text');
                        if (Utils.isEmpty(text)) {
                          return;
                        }
                      },
                      // autofocus: true,
                      decoration: InputDecoration(
                        suffixIcon: IconButton(
                          padding: EdgeInsets.all(2.0),
                          icon: Icon(
                            Icons.qr_code_scanner,
                            size: 28,
                            color: MyAppTheme.nearlyBlue,
                          ),
                          onPressed: () {
                            // requestPermissions();
                            // Utils.scanBarcode(context);
                            Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                              return ScanCode();
                            })).then((text) {
                              if (text == null) {
                                return;
                              }
                              setState(() {
                                textEditingController.text = text;
                              });
                              print(text); //拿到扫描结果
                            });
                          },
                        ),
                        border: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: MyAppTheme.nearlyBlue,
                          ),
                          borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                          // 设置焦点之外的边框颜色
                          borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                          // 设置焦点时的边框颜色
                          borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                        ),
                        hintText: "scan new inbound lpn",
                        filled: true,
                        fillColor: MyAppTheme.white,
                        //隐藏下划线
                        //border: InputBorder.none,
                        hintStyle: TextStyle(color: Colors.grey),
                        contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                      ),
                      onChanged: (text) {
                        code = text;
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),
          Visibility(visible: Utils.getIntegerisEmpty(finalProcessQr.retape) == 1 ? true : false, child: setPhotoView("Retaped Photo:  ", 3, bolPhoto)),
        ],
      ),
    );
  }

  Container setPhotoView(String hintText, int type, PhotoBean photoBean) {
    return Container(
      height: 70,
      margin: const EdgeInsets.only(left: 0, top: 10, right: 0, bottom: 0),
      width: double.infinity,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Expanded(
            flex: 1, //设置权重
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Text(
                  '*',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: MyAppTheme.red, fontSize: 12.0),
                ),
                Text(
                  hintText,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
                ),
              ],
            ),
          ),
          Expanded(
              flex: 2, //设置权重
              child: Row(
                children: [
                  Container(
                    width: 70,
                    height: 70,
                    child: Stack(
                      children: <Widget>[
                        GestureDetector(
                          onTap: () {
                            // 请求焦点
                            FocusScope.of(context).requestFocus(FocusNode());
                            index = type;
                            ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? pickImages(context) : imgFileDialog(photoBean, Constants.baseImgUrl);
                          },
                          child: photoBean.image == null
                              ? (photoBean.urlImg == null
                                  ? Image.asset(
                                      'assets/images/add.png',
                                      width: 70,
                                      height: 70,
                                      fit: BoxFit.cover,
                                    )
                                  : Image.network(
                                      Constants.baseImgUrl + photoBean.urlImg,
                                      width: 70,
                                      height: 70,
                                      fit: BoxFit.cover,
                                    ))
                              : Image.file(
                                  photoBean.image,
                                  width: 70,
                                  height: 70,
                                  fit: BoxFit.cover,
                                ),
                        ),
                        Visibility(
                          visible: ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? false : true,
                          child: Positioned(
                            top: 2.0,
                            right: 2.0,
                            child: GestureDetector(
                              onTap: () {
                                setState(() {
                                  photoBean.urlImg = null;
                                  photoBean.image = null;
                                });
                              },
                              child: Image.asset(
                                'assets/images/ic_delete_menu.png',
                                width: 15,
                                height: 15,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Expanded(
                    flex: 2, //设置权重
                    child: Text(
                      '',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.red, fontSize: 12.0),
                    ),
                  ),
                ],
              )),
        ],
      ),
    );
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    bolPhoto.urlImg = path;

    if (isSubmit) {
      submitData();
    }
  }

  @override
  void setNext() {
    ToastContext().init(context);
    submitData();
  }

  void submitData() {
    checkSubmit();
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      skuEditingController.text = "";
      hint = "";
      bolPhoto = new PhotoBean();
    });
  }

  void checkSubmit() async {
    FinalProcessQr finalProcessQrSubmit = new FinalProcessQr();
    finalProcessQrSubmit.batchNo = finalProcessQr.batchNo;
    finalProcessQrSubmit.oldIbLpn = finalProcessQr.oldIbLpn;
    finalProcessQrSubmit.newIbLpn = finalProcessQr.newIbLpn;
    finalProcessQrSubmit.newObLpn = finalProcessQr.newObLpn;
    finalProcessQrSubmit.returnBatchDetailId = finalProcessQr.returnBatchDetailId;
    finalProcessQrSubmit.trackingCode = finalProcessQr.trackingCode;
    finalProcessQrSubmit.type = finalProcessQr.type;
    finalProcessQrSubmit.sku = finalProcessQr.sku;
    finalProcessQrSubmit.newSku = finalProcessQr.newSku;
    finalProcessQrSubmit.quantity = finalProcessQr.quantity;
    finalProcessQrSubmit.account = finalProcessQr.account;
    finalProcessQrSubmit.label = finalProcessQr.label;
    finalProcessQrSubmit.openLassSku = finalProcessQr.openLassSku;
    finalProcessQrSubmit.retape = finalProcessQr.retape;
    finalProcessQrSubmit.accountId = finalProcessQr.accountId;

    finalProcessQrSubmit.newIbLpn = textEditingController.text;

    ToastContext().init(context);
    if (finalProcessQrSubmit.type == "D") {
      //指定销毁
      if (Utils.isEmpty(textEditingController.text)) {
        Toast.show("Please input new inbound lpn", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
      finalProcessQrSubmit.newIbLpn = (textEditingController.text);

      finalProcessQrSubmit.openLassSku = (skuEditingController.text);
      if (Utils.isEmpty(skuEditingController.text)) {
        Toast.show("Please input sku/barcode", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
    }
    if (finalProcessQrSubmit.type == "D2") {
      //系统销毁
      if (Utils.isEmpty(textEditingController.text)) {
        Toast.show("Please input new inbound lpn", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
      finalProcessQrSubmit.newIbLpn = (textEditingController.text);

      finalProcessQrSubmit.openLassSku = (skuEditingController.text);
      if (Utils.isEmpty(skuEditingController.text)) {
        Toast.show("Please input sku/barcode", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
    }
    if (finalProcessQrSubmit.type == "P") {
      //上架
      if (Utils.isEmpty(textEditingController.text)) {
        Toast.show("Please input new inbound lpn", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
      finalProcessQrSubmit.newIbLpn = (textEditingController.text);

      finalProcessQrSubmit.newSku = (skuEditingController.text);
      if (Utils.isEmpty(skuEditingController.text)) {
        Toast.show("Please input sku/barcode", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
    }
    if (finalProcessQrSubmit.type == "R") {
      //返还客户
      if (Utils.isEmpty(textEditingController.text)) {
        Toast.show("Please input new outbound lpn", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
      finalProcessQrSubmit.newIbLpn = (textEditingController.text);
    }

    if (Utils.getStringisInteger(finalProcessQr.retape) == 1) {
      if (bolPhoto.image == null) {
        Toast.show("Please add retaped photo", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
      if (Utils.isEmpty(bolPhoto.urlImg)) {
        fileUpload(finalProcessQr.trackingCode, "FinalProcessRP", bolPhoto.image, "retape", 0, position, true, true);
        return;
      }
      if (!Utils.isEmpty(bolPhoto.urlImg)) {
        finalProcessQrSubmit.retapedPhoto = bolPhoto.urlImg;
      }
    }

    String json = jsonEncode(finalProcessQrSubmit);
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context, title: "Submit...");
    } catch (e) {
      e.toString();
    }
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.returnSubmit, method: BaseMethod.post, data: json);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      FinalProcessReturn finalProcessReturn = FinalProcessReturn.fromJson(baseResponse.data);
      if (finalProcessReturn == null) {
        Navigator.pop(context, true);
        return;
      }
      Navigator.pop(context, finalProcessReturn);
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }
}
